﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WorkRecord.CommonClass;

namespace WorkRecord.AdminMana.Ajax
{
    public partial class AjaxService : System.Web.UI.Page
    {
        #region 页面加载 --------------------------------------------------------
        protected void Page_Load(object sender, EventArgs e)
        {
            string methodName = Request.QueryString["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (method == null) throw new Exception("方法" + methodName + "不存在!");

            try
            {
                BeforeInvoke(methodName);
                method.Invoke(this, null);
            }
            catch (Exception ex)
            {
                Hashtable result = new Hashtable();
                result["error"] = -1;
                result["message"] = ex.Message;
                result["stackTrace"] = ex.StackTrace;
                String json = JSON.Encode(result);
                Response.Clear();
                Response.Write(json);
            }
            finally
            {
                AfterInvoke(methodName);
            }
        }
        #endregion

        #region 权限管理---------------------------------------------------------
        protected void BeforeInvoke(String methodName)
        {
            //Hashtable user = GetUser();
            //if (user.role == "admin" && methodName == "remove") throw .      
        }
        #endregion

        #region 日志管理---------------------------------------------------------
        protected void AfterInvoke(String methodName)
        {

        }
        #endregion


        public void GetCategory()
        {
            var key = Request["key"] ?? string.Empty;
            var dt =
                new DataAccess().readdata(string.Format("select * from JourneyCategory {0} order by Sort",
                    string.IsNullOrEmpty(key) ? string.Empty : " where CategoryName like '%" + key + "%'"));

            String json = JSON.Encode(dt);
            Response.Write(json);
        }
        public void GetUser()
        {
            string userAccount = Request["userAccount"] ?? string.Empty;

            //索引
            int pageIndex = Convert.ToInt32(Request["pageIndex"]) + 1;
            int pageSize = Convert.ToInt32(Request["pageSize"]);
            //字段排序
            String sortField = Request["sortField"]??"username";
            String sortOrder = string.IsNullOrEmpty(Request["sortOrder"]) ? "" : Request["sortOrder"].ToLower();

            var obj = new DataAccess();

            var dtCount =
                obj.readdata(string.Format("select count(*) from T_Sys_User where state=1 and (username like '%{0}%' OR realname like '%{0}%')",
                    userAccount));

            var dt =
                obj.readdata(string.Format("select * from (select *,ROW_NUMBER() over(order by {0} {1}) as rid  from T_Sys_User where state=1 and (username like '%{2}%' OR realname like '%{2}%'))t where rid>{3} and rid<={4}",
                        sortField, sortOrder, userAccount, (pageIndex - 1)*pageSize, pageIndex*pageSize));

            Hashtable result = new Hashtable();
            result["data"] = dt;
            result["total"] = dtCount.Rows[0][0];
            String json = JSON.Encode(result);
            Response.Write(json);
        }

        public void GetUserCategoryMapping()
        {
            var categoryid = Request["categoryid"] ?? string.Empty;
            var useraccount = Request["useraccount"] ?? string.Empty;

            //索引
            int pageIndex = Convert.ToInt32(Request["pageIndex"]) + 1;
            int pageSize = Convert.ToInt32(Request["pageSize"]);
            //字段排序
            String sortField = "m.ID";//Request["sortField"]??
            String sortOrder = string.IsNullOrEmpty(Request["sortOrder"]) ? "" : Request["sortOrder"].ToLower();

            var obj = new DataAccess();

            string tabSql = string.Format(@"select * from (
                                            SELECT u.username,u.realname,m.CategoryName,m.ID,row_number() over(order by {0} {1}) as rid
                                            FROM [T_Sys_User] u 
                                            INNER JOIN (select distinct jcm.useraccount,jc.CategoryName,jc.ID 
                                                        from JourneyCategoryUserMapping jcm 
				                                        LEFT JOIN JourneyCategory jc ON jcm.CategoryID=jc.ID) m ON u.username=m.useraccount
                                        WHERE (u.username like '%{2}%'  OR u.realname like '%{2}%') {3}
                                        )t where rid>{4} and rid<={5}", sortField, sortOrder, useraccount,
                (string.IsNullOrEmpty(categoryid) ? string.Empty : " and m.ID='" + categoryid + "'"),
                (pageIndex - 1)*pageSize, pageIndex*pageSize);

            string sql = string.Format(@"SELECT count(*)
  FROM [T_Sys_User] u 
  INNER JOIN (select distinct jcm.useraccount,jc.CategoryName,jc.ID from JourneyCategoryUserMapping jcm 
				LEFT JOIN JourneyCategory jc ON jcm.CategoryID=jc.ID) m ON u.username=m.useraccount
 WHERE (u.username like '%{0}%'  OR u.realname like '%{0}%') {1}", useraccount,
                (string.IsNullOrEmpty(categoryid) ? string.Empty : " and m.ID='" + categoryid + "'"));
            var dtCount = obj.readdata(sql);
            var dt = obj.readdata(tabSql);



            Hashtable result = new Hashtable();
            result["data"] = dt;
            result["total"] = dtCount.Rows[0][0];
            String json = JSON.Encode(result);
            Response.Write(json);
        }

        public void DeleteJCategoryUserMapping()
        {
            var ids = Request["ids"] ?? string.Empty;
            var accounts = Request["accounts"] ?? string.Empty;

            if (!string.IsNullOrEmpty(ids.Trim()) && !string.IsNullOrEmpty(accounts))
            {
                var idArr = ids.Split(',');
                var accountArr = accounts.Split(',');
                var obj = new DataAccess();
                for (var i = 0; i < idArr.Length; i++)
                {
                    obj.datacmd(
                        string.Format(
                            "delete from JourneyCategoryUserMapping where CategoryID='{0}' and UserAccount='{1}'",
                            idArr[i], accountArr[i]));
                }
            }
            Hashtable result = new Hashtable();
            result["res"] = "操作成功";
            result["error"] = "";
            String json = JSON.Encode(result);
            Response.Write(json);
        }

        public void AddJCategoryUserMapping()
        {
            var categoryid = Request["categoryid"] ?? string.Empty;
            var usersAccount = Request["usersAccount"] ?? string.Empty;
            if (!string.IsNullOrEmpty(categoryid) && !string.IsNullOrEmpty(usersAccount))
            {
                var arrAccount = usersAccount.Trim(',').Split(',');
                var obj = new DataAccess();
                foreach (var account in arrAccount)
                {
                    var dt =
                        obj.readdata(
                            string.Format(
                                "select * from JourneyCategoryUserMapping where CategoryID='{0}' and UserAccount='{1}'",
                                categoryid, account));
                    if(dt!=null&&dt.Rows.Count>0) continue;

                    obj.datacmd(string.Format("insert into JourneyCategoryUserMapping Values('{0}','{1}')", categoryid,
                        account));
                }
            }
            Hashtable result = new Hashtable();
            result["res"] = "操作成功";
            result["error"] = "";
            String json = JSON.Encode(result);
            Response.Write(json);
        }

        public void EidtCategory()
        {
            var action = Request["Action"] ?? string.Empty;
            var id = Request["id"] ?? string.Empty;
            var categoryName = Request["categoryName"] ?? string.Empty;
            var Sort = Request["Sort"] ?? string.Empty;
            var obj = new DataAccess();
            switch (action)
            {
                case "Insert":
                    obj.datacmd(
                        string.Format("insert into JourneyCategory(CategoryName,Sort) Values('" + categoryName + "','" +
                                      Sort + "')"));
                    break;
                case "Update":
                    if (!string.IsNullOrEmpty(id))
                        obj.datacmd(
                            string.Format("update JourneyCategory set CategoryName='{0}',Sort='{1}' where ID='{2}'",
                                categoryName, Sort, id));
                    break;
                case "Delete":
                    obj.datacmd(string.Format("delete from JourneyCategory where ID='{0}';" +
                                              "delete from JourneyCategoryUserMapping where CategoryID='{0}'", id));

                    break;
            }
            Hashtable result = new Hashtable();
            result["res"] = "操作成功";
            result["error"] = "";
            String json = JSON.Encode(result);
            Response.Write(json);
        }

        public void GetUserPermission()
        {
            var username = Request["username"] ?? string.Empty;
            var type = Request["type"] ?? string.Empty;

            //索引
            int pageIndex = Convert.ToInt32(Request["pageIndex"]) + 1;
            int pageSize = Convert.ToInt32(Request["pageSize"]);
            //字段排序
            String sortField = Request["sortField"] ?? "ViewToUserAccount";
            if (string.IsNullOrEmpty(sortField))
                sortField = "ViewToUserAccount";
            String sortOrder = string.IsNullOrEmpty(Request["sortOrder"]) ? "" : Request["sortOrder"].ToLower();


            var obj = new DataAccess();

            string tabSql =
                string.Format(@"select * from (select *,row_number() over(order by {0} {1}) as rid from JourneyUserPermission 
left join T_Sys_User  ON ViewToUserAccount=username
where UserAccount='{2}' and type='{3}')t where rid>{4} and rid<={5}", sortField, sortOrder, username, type,
                    (pageIndex - 1)*pageSize, pageIndex*pageSize);

            string sql = string.Format(@"select count(*) from JourneyUserPermission 
left join T_Sys_User  ON ViewToUserAccount=username
where UserAccount='{0}' and type='{1}'", username, type);

            var dtCount = obj.readdata(sql);
            var dt = obj.readdata(tabSql);



            Hashtable result = new Hashtable();
            result["data"] = dt;
            result["total"] = dtCount.Rows[0][0];
            String json = JSON.Encode(result);
            Response.Write(json);
        }

        public void AddUserPermission()
        {
            var username = Request["username"] ?? string.Empty;
            var type = Request["type"] ?? string.Empty;
            var viewToUserAccount = Request["viewToUserAccount"] ?? string.Empty;
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(viewToUserAccount))
            {
                var arrAccount = viewToUserAccount.Trim(',').Split(',');
                var obj = new DataAccess();
                foreach (var account in arrAccount)
                {
                    var dt =
                        obj.readdata(
                            string.Format(
                                "select * from JourneyUserPermission where UserAccount='{0}' and ViewToUserAccount='{1}' and type='{2}'",
                                username, account, type));
                    if (dt != null && dt.Rows.Count > 0) continue;

                    obj.datacmd(string.Format("insert into JourneyUserPermission Values('{0}','{1}','{2}')", username,
                        account, type));
                }
            }
            Hashtable result = new Hashtable();
            result["res"] = "操作成功";
            result["error"] = "";
            String json = JSON.Encode(result);
            Response.Write(json);
        }

        public void DeleteUserPermission()
        {
            var userAccount = Request["userAccount"] ?? string.Empty;
            var type = Request["type"] ?? string.Empty;
            var viewToUserAccounts = Request["viewToUserAccounts"] ?? string.Empty;

            if (!string.IsNullOrEmpty(userAccount) && !string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(viewToUserAccounts))
            {
                var arrAccount = viewToUserAccounts.Trim(',').Split(',');
                var obj = new DataAccess();
                foreach (var account in arrAccount)
                {
                    obj.datacmd(
                        string.Format(
                            "delete from JourneyUserPermission where UserAccount='{0}' and ViewToUserAccount='{1}' and type='{2}'",
                            userAccount, account, type));
                }
            }
            Hashtable result = new Hashtable();
            result["res"] = "操作成功";
            result["error"] = "";
            String json = JSON.Encode(result);
            Response.Write(json);
        }
    }
}